package main

import (
"go.mongodb.org/mongo-driver/mongo/options"
"time"
"go.mongodb.org/mongo-driver/mongo"
"context"
"fmt"
)


type LogRecord struct {
	JobName     string      `bson:"jobNmae"`//任务名
	Command     string      `bson:command`//shell命令
	Err         string      `bson:err`//错误输出
	Content     string      `bson:content`//脚本输出
	TimePoint   TimePoint   `bson:"timePoint"`//时间信息
}
type TimePoint struct {
	StartTime   int64   `bson:"startTime"`
	EndTime     int64   `bson:"endTime"`
}

type JobNameFilter struct {
	JobName     string      `bson:"jobNmae"`//任务名
}

type TimeFilter struct {
	Before int64 `bson:"$lt"`
}

type DelCommand struct {
	DelTime TimeFilter `bson:"timePoint.startTime"`
}
//学习使用mongodb
func main() {
	var (
		client      *mongo.Client
		database    *mongo.Database
		collection  *mongo.Collection
		curser      *mongo.Cursor
		delRest     *mongo.DeleteResult
		err error
	)
	con := context.TODO()
	//1、建立连接
	opt := options.Client()
	opt.SetConnectTimeout(5*time.Second).ApplyURI("mongodb://10.2.111.241:27017")
	if client,err = mongo.Connect(con,opt); err != nil {
		fmt.Println(err)
		return
	}
	//2、选择数据库
	database = client.Database("cron")
	//3、选择表my_collection
	collection = database.Collection("log")
	record := &LogRecord{
		JobName: "job",
		Command: "echo hello",
		Err:     "",
		Content: "hello",
		TimePoint: TimePoint{
			StartTime: time.Now().Unix() - 10, EndTime: time.Now().Unix() + 10,
		},
	}
	//插入一个
	if insertRes, err := collection.InsertOne(con, record); err != nil {
		fmt.Println(err)
		return
	} else {
		fmt.Println(insertRes.InsertedID)
	}

	//插入多个
	interMany := []interface{}{record,record}
	if insertManyRes, err := collection.InsertMany(con,interMany);err != nil {
		fmt.Println(err)
		return
	}else {
		for _,v :=  range insertManyRes.InsertedIDs {
			fmt.Println(v)
		}
	}

	//查询操作
	filter := &JobNameFilter{
		JobName:"job",
	}
	limit := int64(2)
	skip := int64(1)
	findOpt := &options.FindOptions{
		Limit:&limit,
		Skip:&skip,
	}
	if curser,err = collection.Find(con,filter,findOpt);err != nil {
		fmt.Println(err)
		return
	}
	//释放游标
	defer curser.Close(con)
	result := &LogRecord{}
	for curser.Next(con) {
		curser.Decode(result)
		fmt.Println("结果是：",*result)
	}

	//删除操作：删除创建时间早于当前时间的日志
	delCommand := &DelCommand{
		DelTime:TimeFilter{
			Before:time.Now().Unix(),
		},
	}

	if delRest,err = collection.DeleteMany(con,delCommand);err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("删除了：",delRest.DeletedCount,"条")
	return
}